/**
 * 
 */
//setp1 立即调用的函数
+function($) {
	"use strict";
//setp2 插件核心代码
	var BsTabs = function(element, options) {
		this.options = options;
		this.$element = $(element);
		
		this._init();
	};
	
	BsTabs.VERSION  = '1.0.0';
	
	BsTabs.DEFAULTS = {
	    
	}
	
	//初始化tab组件
	BsTabs.prototype._init = function () {
		this.$element.addClass("bstabs-wrapper");
		this.$element.html("");
		this._initTab();
		this._initRollLeftButton();
		this._initPageTabs();
		this._initRollRightButton();
		this._initDropdownMenu();
		this._initContainer();
		
		
		
		/*
			<button class="roll-nav roll-left tabLeft">
			<i class="fa fa-backward"></i>
	    </button>
	    */
	}
	
	//初始tab
	BsTabs.prototype._initTab = function() {
		this.$element.append('<div class="row bs-tabs"></div>');
		this.$tab = this.$element.find(".bs-tabs");
	};
	
	//初始化向左边滚动的按钮
	BsTabs.prototype._initRollLeftButton = function() {
		var $bstab = this;
		this.$tab.append('<button class="roll-nav roll-left tabLeft"><i class="fa fa-backward"></i></button>');
		
		this.$tab.find(".tabLeft").on("click", function(){
			var container = $bstab.$tab.find(".page-tabs-content");
			var marginLeft = parseInt(container.css("margin-left"));
			if(marginLeft>=0) {
				return;
			}
			var tabWidth = 0;
			var lastHideElement = undefined;
			var firstVisableElement = undefined;
			$bstab.$tab.find(".menuTab").each(function(){
				var ele = $(this)[0];
				tabWidth += ele.offsetWidth;
				if(tabWidth+marginLeft>0&&firstVisableElement==undefined) {
					firstVisableElement = ele;
					return false;
				}
				lastHideElement = ele;
			});
			$bstab.goRight(lastHideElement.offsetWidth);
		});
	};
	
	//初始化向右边滚动的按钮
	BsTabs.prototype._initRollRightButton = function() {
		var $bstab = this;
		this.$tab.append('<button class="roll-nav roll-right tabRight"><i class="fa fa-forward"></i></button>');
		
		this.$tab.find(".tabRight").on("click", function(){
			var tabLeft = $bstab.$tab.find(".tabLeft");
			var tabRight = $bstab.$tab.find(".tabRight");
			var tabMaxWidth = tabRight[0].offsetLeft - tabLeft[0].offsetLeft - tabLeft[0].offsetWidth;
			
			var container = $bstab.$tab.find(".page-tabs-content");
			var marginLeft = parseInt(container.css("margin-left"));
			var tabWidth = 0;
			var firstVisableElement = undefined;
			$bstab.$tab.find(".menuTab").each(function(){
				var ele = $(this)[0];
				tabWidth += ele.offsetWidth;
				if(tabWidth+marginLeft>0&&firstVisableElement==undefined) {
					firstVisableElement = ele;
				}
			});
			if(tabWidth+marginLeft<=tabMaxWidth) {
				return;
			}
			$bstab.goLeft(firstVisableElement.offsetWidth);
		});
	};
	
	//初始化tab导航
	BsTabs.prototype._initPageTabs = function() {
		this.$tab.append('<nav class="page-tabs menuTabs">'+
							        '<div class="page-tabs-content">'+
//							            '<a class="menuTab active" data-id="index_v1.html">首页</a>'+
//							        	'<a class="menuTab" data-id="graph_echarts.html">百度ECharts <i class="fa fa-times-circle"></i></a>'+
							    	'</div>'+
						    '</nav>');
	};
	
	//初始化tab下拉菜单
	BsTabs.prototype._initDropdownMenu = function() {
		var $bstab = this;
		this.$tab.append('<div class="btn-group roll-nav roll-right">'+
		        				'<button class="dropdown tabClose" data-toggle="dropdown">'+
		        					'操作<span class="caret"></span>'+
        						'</button>'+
								'<ul role="menu" class="dropdown-menu dropdown-menu-right">'+
									'<li class="tabShowActive"><a>定位当前选项卡</a>'+
									'</li>'+
									'<li class="tabActiveRefresh"><a>刷新当前选项卡</a>'+
									'</li>'+
									'<li class="divider"></li>'+
									'<li class="tabCloseAll"><a>关闭全部选项卡</a>'+
									'</li>'+
									'<li class="tabCloseOther"><a>关闭其他选项卡</a>'+
									'</li>'+
								'</ul>'+
							'</div>');
		
		this.$tab.find(".tabShowActive").on("click", function(){
			$bstab.tabShowActive();
		});
		this.$tab.find(".tabCloseAll").on("click", function(){
			$bstab.tabCloseAll();
		});
		this.$tab.find(".tabCloseOther").on("click", function(){
			$bstab.tabCloseOther();
		});
		this.$tab.find(".tabActiveRefresh").on("click", function(){
			$bstab.tabActiveRefresh();
		});
	};
	
	//初始化页面容器
	BsTabs.prototype._initContainer = function() {
		this.$element.append('<section class="bs-content"></section>');
		this.$container = this.$element.find(".bs-content");
	};
	
    
	//新建一个tab
	BsTabs.prototype.newTab = function(url, title, enableClose, isActive) {
		if(isActive==undefined) {
			isActive = true;
		}
		if(enableClose==undefined) {
			enableClose = true;
		}
		if(title==undefined) {
			title = url;
		}
		if(!this._checkIsOpen(url)) {
			this._addTab(url, title, enableClose);
		}
		if(isActive) {
			this.gotoTab(url);
		}
	}; 
	
	//替换当前tab内容
	BsTabs.prototype.replaceTab = function(url) {
		this.$container.find("> .tab-content:eq("+this.$currentIndex+")").load(url);
	};
	
	//新建一个tab
	BsTabs.prototype._addTab = function(url, title, enableClose) {
		var urls = this.$urls|| new Array();
		var o = new Object();
		o.url = url;
		o.title = title;
		o.enableClose = enableClose;
		urls.push(o);
		this.$urls = urls;
		
		if(enableClose) {
			this.$tab.find(".page-tabs-content").append('<a href="javascript:;" class="menuTab" data-id="'+url+'">'+title+'<i class="fa fa-times-circle"></i></a>');
		} else {
			this.$tab.find(".page-tabs-content").append('<a href="javascript:;" class="menuTab" data-id="'+url+'">'+title+'</a>');
		}
		
		this.$container.append('<div class="tab-content"></div>');
		this.$container.find("> .tab-content:last").load(url);
		var $bstabs = this;
		this.$tab.find(".menuTab:last").on("click",function(){
			var index = $bstabs.$tab.find(".menuTab").index($(this));
			$bstabs.gotoIndex(index);
		});
		
		this.$tab.find(".menuTab:last").find(".fa-times-circle").on("click",function(e){
			e.stopPropagation();
			var index = $bstabs.$tab.find(".menuTab").index($(this).parents(".menuTab"));
			$bstabs.closeTab(index);
		});
		
		
	}; 
	
	
	
	//检查url是否已经打开
	BsTabs.prototype._checkIsOpen = function(url) {
		if(this.tabIndex(url)>=0) {
			return true;
		}
		return false;
	};
	
	//检查url所在索引
	BsTabs.prototype.tabIndex = function(url) {
		var urls = this.$urls|| new Array();
		for(var i=0;i<urls.length;i++) {
			if(urls[i].url==url) {
				return i;
			}
		}
		return -1;
	};
	
	//关闭指定的tab页，显示右侧的tab页
	BsTabs.prototype.closeTab = function(index) {
		var count = this.$urls.length;
		if(index<0||index>count) {
			return;
		}
		this.$tab.find(".menuTab:eq("+index+")").remove();
		this.$container.find("> .tab-content:eq("+index+")").remove();
		
		this.$urls.splice(index, 1);;
		
		if(this.$currentIndex==index) {
			this.$currentIndex = -1;
			if(index<count-1) {
				this.gotoIndex(index);
			} else {
				this.gotoIndex(index-1);
			}
		} else if(this.$currentIndex>index) {
			this.$currentIndex = this.$currentIndex - 1;
		} 
	};
	
	//检查tab栏的状态，是否可以左右滚动，是否需要自动偏移
	BsTabs.prototype.tabShowActive = function() {
		var tabLeft = this.$tab.find(".tabLeft");
		var tabRight = this.$tab.find(".tabRight");
		var tabMaxWidth = tabRight[0].offsetLeft - tabLeft[0].offsetLeft - tabLeft[0].offsetWidth;
		
		var container = this.$tab.find(".page-tabs-content");
		var marginLeft = parseInt(container.css("margin-left"));
		
		var tabWidth = 0;
		var tabActivieWidth = 0
		var firstVisableElement = undefined;
		var lastHideElement = undefined;
		var activeElement = undefined;
		var isActive = false
		this.$tab.find(".menuTab").each(function(){
			var ele = $(this)[0];
			tabWidth += ele.offsetWidth;
			if(tabWidth+marginLeft>0&&firstVisableElement==undefined) {
				firstVisableElement = ele;
			} else if(firstVisableElement==undefined) {
				lastHideElement = ele;
			}
			if(isActive==false) {
				tabActivieWidth += ele.offsetWidth;
			}
			if($(this).hasClass("active")) {
				activeElement = ele;
				isActive = true;
			}
		});
		
		tabWidth = tabWidth + marginLeft;
		tabActivieWidth = tabActivieWidth + marginLeft;
		if(tabActivieWidth>tabMaxWidth*2/3 && tabActivieWidth<tabMaxWidth) {
			var dis = tabActivieWidth - tabMaxWidth/2;
			var prevEle = $(firstVisableElement);
			var right = 0;
			while(dis>0&&prevEle&&prevEle.length>0) {
				dis -= prevEle[0].offsetWidth;
				if(tabWidth<=tabMaxWidth) {
					break;
				}
				tabWidth -= prevEle[0].offsetWidth;
				right += prevEle[0].offsetWidth;
				prevEle = prevEle.next();
			}
			this.goLeft(right);
		} else if(tabActivieWidth<tabMaxWidth/3) {
			var dis = tabMaxWidth/2 - tabActivieWidth;
			dis = Math.min(dis,marginLeft*(-1));
			var prevEle = $(lastHideElement);
			var right = 0;
			while(dis>0&&prevEle&&prevEle.length>0) {
				dis -= prevEle[0].offsetWidth;
				right += prevEle[0].offsetWidth;
				prevEle = prevEle.prev();
			}
			this.goRight(right);
		} else if(tabActivieWidth>tabMaxWidth) {
			var left = 0;
			while(tabActivieWidth>tabMaxWidth*2/3&&firstVisableElement) {
				tabActivieWidth -= firstVisableElement.offsetWidth;
				if(tabWidth<=tabMaxWidth) {
					break;
				}
				tabWidth -= firstVisableElement.offsetWidth;
				left += firstVisableElement.offsetWidth;
				firstVisableElement = $(firstVisableElement).next()[0];
			}
			this.goLeft(left);
		} 
		
	};
	
	
	//tab栏向左偏移
	BsTabs.prototype.goLeft = function(value) {
		var container = this.$tab.find(".page-tabs-content");
		container.css("margin-left",(parseInt(container.css("margin-left"))-value)+"px");
	};
	
	//tab栏向右偏移
	BsTabs.prototype.goRight = function(value) {
		var container = this.$tab.find(".page-tabs-content");
		container.css("margin-left",(parseInt(container.css("margin-left"))+value)+"px");
	};
	
	//重置tab栏
	BsTabs.prototype.reset = function() {
		this.$tab.find(".page-tabs-content").css("margin-left", "0");
	};
	
	//切换到指定的url tab页
	BsTabs.prototype.gotoTab = function(url) {
		var index = this.tabIndex(url);
		if(index>=0) {
			this.gotoIndex(index);
		}
	};
	
	//切换到指定的index tab页
	BsTabs.prototype.gotoIndex = function(index) {
		if(this.$currentIndex==undefined) {
			this.$currentIndex = -1;
		}
		var currentIndex = this.$currentIndex;
		if(currentIndex!=index&&index>=0) {
			this.$tab.find(".menuTab").removeClass("active");
			this.$tab.find(".menuTab:eq("+index+")").addClass("active");
			
			this.$container.find("> .tab-content").hide();
			this.$container.find("> .tab-content:eq("+index+")").show();
		}
		this.$currentIndex = index;
		
		this.tabShowActive();
		//this.tabActiveRefresh();此处消销掉，解决新TAB在打开时有刷新操作。
	};
	
	//关闭所有选项卡
	BsTabs.prototype.tabCloseAll = function() {
		var count = this.$urls.length;
		for(var i=count-1;i>0;i--) {
			this.closeTab(i);
		}
	};
	
	//关闭其他选项卡
	BsTabs.prototype.tabCloseOther = function() {
		var count = this.$urls.length;
		var currentIndex = this.$currentIndex;
		for(var i=count-1;i>0;i--) {
			if(currentIndex!=i) {
				this.closeTab(i);
			}
		}
		this.reset();
	};
	
	//刷新当前选项卡
	BsTabs.prototype.tabActiveRefresh = function() {
		this.tabShowActive();
		var urls = this.$urls|| new Array();
		this.$container.find("> .tab-content:eq("+this.$currentIndex+")").load(urls[this.$currentIndex].url);
	};
	
	
//setp3 jquery插件定义	
	var allowedMethods = [
	                      'newTab',
	                      'replaceTab',
	                      'closeTab',
                      	  'tabShowActive',
                      	  'tabCloseAll',
                      	  'tabCloseOther',
                      	  'tabActiveRefresh'
	                      ];
	
	var old = $.fn.bstabs;
	$.fn.bstabs = function(option) {
		var value,
	    	args = Array.prototype.slice.call(arguments, 1);
		this.each(function () {
		    var $this = $(this),
		        data = $this.data('bs.bstabs'),
		        options = $.extend({}, BsTabs.DEFAULTS, $this.data(),
		            typeof option === 'object' && option);
		
		    if (typeof option === 'string') {
		        if ($.inArray(option, allowedMethods) < 0) {
		            throw new Error("Unknown method: " + option);
		        }
		        if (!data) {
		            return;
		        }
		        value = data[option].apply(data, args);
		        if (option === 'destroy') {
		            $this.removeData('bs.bstabs');
		        }
		    }
		    if (!data) {
		        $this.data('bs.bstabs', (data = new BsTabs(this, options)));
		    }
		});
		return typeof value === 'undefined' ? this : value;
	};
	
	$.fn.bstabs.Constructor = BsTabs;

//setp4 防冲突处理
	$.fn.bstabs.noConflict = function() {
		$.fn.bstabs = old;
		return this;
	};
}(window.jQuery);